package top.ajunnihao.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;

/**
 * <p>
 * MyBatisPlus 全局配置
 * </p>
 */
@Configuration
@MapperScan("top.ajunnihao.core.mapper")
@EnableTransactionManagement // 开启事务管理器，默认就是开启的
public class MyBatisPlusConfig {

    /**
     * 乐观锁组件 OptimisticLockerInterceptor(乐观锁拦截器)
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 分页插件 PaginationInterceptor(分页拦截器)
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * MyBatis Plus 自定义元数据处理器，来处理自动填充策略
     */
    @Component
    static class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
        /**
         * 插入时的填充策略 => gmtCreate, gmtUpdate
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            boolean gmtCreateFlag = metaObject.hasSetter("gmtCreate");
            boolean gmtUpdateFlag = metaObject.hasSetter("gmtUpdate");
            if (gmtCreateFlag)
                this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now());
            if (gmtUpdateFlag)
                this.strictInsertFill(metaObject, "gmtUpdate", LocalDateTime.class, LocalDateTime.now());
        }

        /**
         * 更新时的填充策略 => gmtUpdate
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            boolean gmtUpdateFlag = metaObject.hasSetter("gmtUpdate");
            if (gmtUpdateFlag)
                this.strictUpdateFill(metaObject, "gmtUpdate", LocalDateTime.class, LocalDateTime.now());
        }
    }

}
